<template>
  <el-container
    direction="vertical"
    v-loading="pageLoading"
    element-loading-text="遴选内容加载中.."
    element-loading-spinner="el-icon-loading">
    <el-header
      class="examinateHeader"
      height="80px"
      v-if="testPaper!== null">
      <h2>
        {{testPaper.selectRecordName}}（{{testPaper.totalScore}}分）——时长：{{testPaper.testTime}}分钟
        <span style="float: right">倒计时：{{countDownTip}}</span>
      </h2>

    </el-header>
    <el-main
      class="questionBody"
      v-if="problemList.length!=0">
      <div v-for="(item,index1) in problemList" v-if="index1===currentProblemIndex" :key="index1">
        <div class="queContent">
          <p>
            <el-tag v-if="item.question.problemType === 0">单选</el-tag>
            <el-tag v-if="item.question.problemType === 1">多选</el-tag>
            <el-tag v-if="item.question.problemType === 2">填空</el-tag>
            <el-tag v-if="item.question.problemType === 3">判断</el-tag>
            <el-tag v-if="item.question.problemType === 4">自定义主观题</el-tag>
            {{ index1 + 1 }}.
            <span>{{ item.question.problemCotent }}</span>
          </p>
        </div>
        <div class="quetanswer">
          <el-form @submit.native.prevent :model="examForm">
            <el-form-item v-if="item.question.problemType === 0">
              <!--单选-->
              <el-radio-group v-model="examForm.answer" type="vertical" @change="ToYouranswer">
                <el-radio
                  border
                  v-if="item.selections.length !== 0"
                  v-for="(answer,index) in item.selections"
                  :label="answer.problemId"
                  :key="index"
                  class="radio-item m-0"
                  style="margin-left: 0">
                  {{ answer.problemCotent }}
                </el-radio>
                <!--                class="block m-0 radio-item">-->
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="item.question.problemType == 1">
              <!--多选-->
              <el-checkbox-group
                v-model="examForm.answerIds"
                :min="0"
                @change="multiAnswerToString"
              >
                <el-checkbox-button
                  class="block m-0 checkbox-item"
                  v-for="(answer2, index3) in item.selections"
                  :label="answer2.problemId"
                  :key="index3"
                >
                  {{ answer2.problemCotent }}
                </el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item v-if="item.question.problemType == 2">
              <!--填空-->
              <el-input
                @input="ToYouranswer"
                class="inputline text-center"
                placeholder="请填空"
                v-model="examForm.answer"
              >
              </el-input>
            </el-form-item>
            <el-form-item v-if="item.question.problemType == 3">
              <!--判断-->
              <el-radio-group v-model="examForm.answer" @change="ToYouranswer">
                <el-radio
                  v-for="(answer3, index4) in item.selections"
                  class="block m-0 radio-item"
                  :label="answer3.problemId"
                  :key="index4"
                  style="margin-left: 0"
                >
                  {{ answer3.problemCotent }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="item.question.problemType == 4">
              <!--自定义主观题-->
              <el-input
                @input="ToYouranswer"
                type="textarea"
                class="inputline text-center"
                placeholder="请答题"
                :autosize="{ minRows: 4, maxRows: 6}"
                v-model="examForm.answer"
              >
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="buttonGroup v-m">
          <el-button
            @click="prevQuestion(item, currentProblemIndex)"
            v-show="prebtnshow"
          >上一题：{{ currentProblemIndex + 1 }}/{{ problemList.length }}
          </el-button>
          <el-button
            @click="nextQuestion(item,currentProblemIndex)"
            v-show="nextbtnshow"
          >下一题：{{ currentProblemIndex + 1 }}/{{ problemList.length }}
          </el-button>
          <el-button @click="answerCommit()" v-show="commitbtnshow"
          >完成答题
          </el-button>
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script>
  import {mapGetters}from 'vuex';
  import {
    getTestPaper,
    commitTheProblem,
    getAnswerHistory,
    finishTest,
  } from './exam.js'
  import elementIcons from "@/views/icons/element-icons";

  export default {
    name: "examIndex",
    data() {
      return {
        examId: null,
        pageLoading: true,
        prebtnshow: false,
        nextbtnshow: true,
        commitbtnshow: false,
        getPaperData: {
          selectRecordId: null,
          type: 2,//考试类型 1-初始评级考试；2-二次遴选考试
        },
        testPaper: null,//试卷信息
        problemList: [],//题目列表
        currentProblemIndex: 0,//当前题目索引
        examForm: {
          examId: null,
          problemId: null,
          answer: null,//填空、判断、单选、主观题绑定的数据
          answerIds: [],//多选绑定的数据
          yourAnswer: "",
        },//每道题提交的表单
        count: null,
        timer: null,
        countDownTip: null,
        finishStatus: false,
      }
    },
    computed:{
      ...mapGetters([
        'roles'
      ])
    },
    watch: {
      currentProblemIndex(val) {
        if (
          this.problemList !== null &&
          this.problemList.length > 1
        ) {
          if (val == this.problemList.length - 1) {
            this.commitbtnshow = true;
            this.prebtnshow = true;
            this.nextbtnshow = false;
          } else if (val == 0) {
            this.prebtnshow = false;
            this.nextbtnshow = true;
            this.commitbtnshow = false;
          } else if (
            val > 0 &&
            val < this.problemList.length - 1
          ) {
            this.prebtnshow = true;
            this.nextbtnshow = true;
            this.commitbtnshow = false;
          }
        } else if (this.problemList.length <= 1) {
          this.commitbtnshow = true;
          this.nextbtnshow = false;
          this.prebtnshow = false;
        }
        this.getProblemRecord();
      },
    },
    created() {
      if (this.$route.query.hasOwnProperty('selectRecordId') == true) {
        this.getPaperData.selectRecordId = this.$route.query.selectRecordId;
        this.getTestPaperInfo();
      }
      if (this.$route.query.hasOwnProperty('testType') == true){
        this.getPaperData.type = this.$route.query.testType;
        this.getTestPaperInfo();
      }
    },
    methods: {
      getTestPaperInfo() {
        const _this = this;
        getTestPaper(this.getPaperData).then(res => {
          _this.pageLoading = true;
          if (res.code === 20000) {
            _this.testPaper = res.data.testPaper;
            _this.problemList = res.data.problems;
            _this.examForm.examId = res.data.examId;
            _this.examId = res.data.examId;
            _this.coutDown();
          }
          _this.pageLoading = false;
        })
      },
      /*多选答案转换成字符串*/
      multiAnswerToString(val) {
        this.examForm.yourAnswer = val.toString();
      },
      /*单选、填空、判断、主观题答案填到youranswer*/
      ToYouranswer(val) {
        this.examForm.yourAnswer = val
      },
      /*获取当前题目的历史作答*/
      getProblemRecord() {
        getAnswerHistory({
          examId: this.examId,
          problemId: this.problemList[this.currentProblemIndex].question.problemId
        }).then(res => {
          if (res.code === 20000) {
            /*历史作答渲染*/
            let answerIds = new Array();
            /*     <el-tag v-if="item.question.problemType === 0">单选</el-tag>
            <el-tag v-if="item.question.problemType === 1">多选</el-tag>
            <el-tag v-if="item.question.problemType === 2">填空</el-tag>
            <el-tag v-if="item.question.problemType === 3">判断</el-tag>
            <el-tag v-if="item.question.problemType === 4">自定义主观题</el-tag>*/
            if (this.problemList[this.currentProblemIndex].question.problemType === 1) {
              /*多选题*/
              let ids = res.data.split(',')
              ids.forEach(function (answer, index) {
                answerIds.push(parseInt(answer))
              });
            } else if (this.problemList[this.currentProblemIndex].question.problemType === 0 || this.problemList[this.currentProblemIndex].question.problemType === 3) {
              /*单选|判断*/
              this.examForm.answer = parseInt(res.data);
            } else {
              this.examForm.answer = res.data;
            }
            this.examForm.yourAnswer = res.data;
            this.examForm.answerIds = answerIds;
          }
        })
      },
      /*上一步按钮*/
      prevQuestion(item, index) {
        this.currentProblemIndex--;
      },
      /*下一步按钮*/
      nextQuestion(item, index) {
        console.log(item)
        this.examForm.problemId = item.question.problemId;
        console.log(this.examForm)
        if (this.examForm.yourAnswer !== "" && this.examForm.yourAnswer !== null) {
          /*执行该题的提交*/
          commitTheProblem(this.examForm).then(res => {
            if (res.code === 20000 && res.data === this.examForm.examId) {
              this.$message({
                type: "success",
                message: "作答成功",
              })
              /*清空答题form*/
              this.examForm.yourAnswer = null;
              this.examForm.answer = null;
              this.examForm.answerIds = [];
              this.currentProblemIndex++;
            }
          })
        } else if (this.examForm.yourAnswer === "" || this.examForm.yourAnswer === null) {
          this.$confirm('该题尚未作答，请答题', '提示', {
            confirmButtonText: '继续答题',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
          }).catch(() => {
          });
        }
      },
      /*完成答题*/
      answerCommit() {
        const _this = this;
        this.examForm.problemId = this.problemList[this.currentProblemIndex].question.problemId;
          if (this.examForm.yourAnswer === "" || this.examForm.yourAnswer === null) {
            if (this.finishStatus == false){
              this.$alert('倒计时结束，无法继续参加遴选', '提示', {
                confirmButtonText: '确定',
                callback: action => {

                  finishTest(this.examForm).then(res => {
                    if (res.code === 20000) {
                      this.$message({
                        type: "success",
                        message: "完成遴选！"
                      })
                      clearInterval(this.timer);
                      this.finishStatus = true;
                      if (_this.getPaperData.type ===1){
                        this.$router.push({
                          name: "examResult",
                          query:{examId:_this.examForm.examId}
                        })
                        this.$store.dispatch('tagsView/delView', this.$route)
                      }else if(_this.getPaperData.type ===2){
                        this.$router.push({
                          name: "employeeDetialInfo",
                          query:{selectRecordId:this.getPaperData.selectRecordId}
                        })
                        this.$store.dispatch('tagsView/delView', this.$route)
                      }

                    }
                  })

                }
              });
            }else{
              this.$confirm('该题尚未作答，请答题', '提示', {
                confirmButtonText: '继续答题',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
              }).catch(() => {
              });
            }
          } else if (this.examForm.yourAnswer !== "" && this.examForm.yourAnswer !== null) {
            finishTest(this.examForm).then(res => {
              if (res.code === 20000) {
                this.$message({
                  type: "success",
                  message: "完成遴选！"
                })
                this.finishStatus = true;
                if (_this.getPaperData.type ===1){
                  this.$router.push({
                    name: "examResult",
                    query:{examId:_this.examForm.examId}
                  })
                  this.$store.dispatch('tagsView/delView', this.$route)
                }else if(_this.getPaperData.type ===2){
                  this.$router.push({
                    name: "employeeDetialInfo",
                    query:{selectRecordId:this.getPaperData.selectRecordId}
                  })
                  this.$store.dispatch('tagsView/delView', this.$route)
                }
              }
            })
          }


      },
      /*倒计时*/
      coutDown() {
        const TIME_COUNT = this.testPaper.testTime * 60;
        let count;
        const _this = this;
        if (!this.timer) {
          count = TIME_COUNT;
          this.timer = setInterval(() => {
            if (count > 0 && count <= TIME_COUNT) {
              count--;
              this.useTime++;
              _this.countDownTip = count + "s";
            } else {
              clearInterval(this.timer);
              this.timer = null;
              //在此处设置完成答题之后的页面
              //提交成绩
              if (this.finishStatus === false) {
                this.answerCommit();
              }
            }
          }, 1000);
        }
      },
    }
  }
</script>

<style scoped>
  @import "../../styles/common.css";
  @import "./examStyle.css";
</style>
